package cn.pconline.autoclub.exception;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class AutoclubExceptionHandler implements HandlerExceptionResolver {

    private static final Logger log = LoggerFactory.getLogger(AutoclubExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
        //String detailMessage = ex.getMessage();
        //X-Requested-With:XMLHttpRequest
        String requestType = request.getHeader("X-Requested-With");
        boolean isAjax = requestType != null && "XMLHttpRequest".equals(requestType);

        Map<String, Object> model = new HashMap<String, Object>();
        long exAt = System.currentTimeMillis();
        log.error("do rqtuest {} catch the {} exception at {}.",request.getRequestURI(), ex.getMessage(), exAt);
        log.error("catch the exception", ex);
        //ex = new AutoclubException(ex);//把异常都转为AutoclubException处理
        
        if (isAjax) {
            JSONBuilder json = new JSONBuilder();
            json.put("statusCode", 300); //后台dwz错误状态吗
            json.put("code", -1); //前台业务判断码
            json.put("message", "提交失败，请检查后重新提交或联系客服人员，非常抱歉... (" + 
                    " " + exAt + ")"); //标识异常发生时间
            model.put("jo", json);
            // 异步请求专用错误响应页
            return new ModelAndView("/error/jsonError", model);
        } else {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);//503
            model.put("ex", ex);
            model.put("exAt", exAt);
            return new ModelAndView("/template/common/notFoundPage", model);
        }
    }
}
